/*
 * Copyright (c) 2012 Robert Burrell Donkin robertburrelldonkin.name
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
 * is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 */
package sekhmet.audio.format;

import java.nio.ByteBuffer;

import javax.sound.sampled.AudioFormat;

import sekhmet.audio.data.AudioData;

abstract class BufferingReader extends DefaultReader {

	public BufferingReader() {
		super();
	}

	protected AudioData build(final AudioFormat format, final long startFrame, final byte[] bytes, int numberOfBytesRead) {
		final long startMillis = Math.round((startFrame * 1000) / format.getFrameRate());
		final long numberOfFrames = numberOfBytesRead / format.getFrameSize();
		final long durationMillis =  Math.round((numberOfFrames * 1000d) / format.getFrameRate()) ;
		
		final ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, numberOfBytesRead);
		return new AudioData(buffer, format, startFrame,startMillis, numberOfFrames, durationMillis);
	}

	protected long nextFrame(final AudioData data) {
		return data.getStartFrame() + data.getNumberOfFrames();
	}

}